package com.yanqu.road.server.cmd.marriage;

import com.yanqu.road.entity.marriage.MarriageInfo;
import com.yanqu.road.entity.servercenter.group.CrossMarriageGroup;
import com.yanqu.road.logic.pb.MarriagePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.marriage.CrossMarriageProto;
import com.yanqu.road.pb.marriage.MarriageProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.marriage.CrossGroupMarriageMgr;
import com.yanqu.road.server.manger.CrossMarriageGroupMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.math.BigInteger;
import java.util.List;

@Cmd(code = Protocol.C_MARRIAGE_REFRESH_SERVER_APPLY, desc = "刷新跨服非指向联姻")
public class CrossMarriageRefreshServerApplyCmd extends CrossCommand {
    private long userId;
    private int childSex;
    private BigInteger minEarnSpeed = BigInteger.ZERO;
    private BigInteger maxEarnSpeed = BigInteger.ZERO;
    private List<MarriageInfo> marriageInfoList;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        CrossMarriageProto.CrossMarriageRefreshServerApplyReqMsg reqMsg = CrossMarriageProto.CrossMarriageRefreshServerApplyReqMsg.parseFrom(packet.getBytes());
        childSex = reqMsg.getChildSex();
        minEarnSpeed = new BigInteger(reqMsg.getMinEarnSpeed());
        maxEarnSpeed = new BigInteger(reqMsg.getMaxEarnSpeed());
        userId = packet.getPlayerId();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        CrossMarriageGroup marriageGroup = CrossMarriageGroupMgr.getCrossMarriageGroupByServerId(serverId);
        if(!CrossMarriageGroupMgr.canCrossMarriage(marriageGroup)){
            ret = GameErrorCode.E_CROSS_MARRIAGE_NO_OPEN;
            return;
        }
        marriageInfoList = CrossGroupMarriageMgr.refreshServerApplyList(marriageGroup.getGroupId(), serverId, userId, childSex, minEarnSpeed, maxEarnSpeed);
    }

    @Override
    public void sendData() {
        CrossMarriageProto.CrossMarriageRefreshServerApplyRespMsg.Builder respMsg = CrossMarriageProto.CrossMarriageRefreshServerApplyRespMsg.newBuilder();
        respMsg.setRet(ret);
        if(0 == ret){
            MarriageProto.MarriageApplyListMsg.Builder listMsg = MarriagePb.parseMarriageApplyListMsg(marriageInfoList);
            respMsg.setDataList(listMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_CROSS_MARRIAGE_REFRESH_SERVER_APPLY_LIST, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }
}
